import * as step from '@flow-step/step-toolkit'
import * as fs from "fs";
import {IParams} from './params'
import {KubernetesCertificate} from '@flow-step/step-toolkit/lib/certificate/certificate'
import {execSync} from 'node:child_process'
import {polyglot} from './i18n'

// sourceFile 直接 chmod 可能存在多个 Job 并发导致 text file busy 问题，拷贝到工作区以区分不同文件
export function copyToTargetBin(sourceBinFile: string, targetBinFile: string) {
    step.debug(`copy binary ${sourceBinFile} to ${targetBinFile}`)
    // 检查目标文件是否存在
    if (fs.existsSync(targetBinFile)) {
        step.debug(`remove ${targetBinFile}`)
        fs.unlinkSync(targetBinFile);
    }
    fs.copyFileSync(sourceBinFile, targetBinFile)

    try {
        const stats = fs.statSync(targetBinFile)
        if ((stats.mode & 0o777) === 0o755) {
            step.debug(`Permissions for ${targetBinFile} is already 755`)
        } else {
            fs.chmodSync(targetBinFile, 0o755)
            step.debug(`Permissions for ${targetBinFile} set to 755`)
        }
    } catch (err) {
        // @ts-ignore
        throw new Error(`Error setting file permissions: ${err.message}`)
    }
    return targetBinFile;
}

export function prepareKubectlArgs(params: IParams, kubernetesCertificate: KubernetesCertificate, kubeDirPath: string) {
    // 新建临时目录存储 kubeConfig 文件
    fs.mkdirSync(kubeDirPath, {recursive: true})
    const kubeConfigPath = `${kubeDirPath}/config`

    let kubectlArgs = ['']
    if (params.clusterType === 'custom' || !kubernetesCertificate.miranaProxy || kubernetesCertificate.miranaProxy === '') {
        if (kubernetesCertificate.kubeConfig === undefined || kubernetesCertificate.kubeConfig === '') {
            throw new Error(polyglot.t("failed_to_obtain_kubernetes_certificate_file"))
        }

        fs.writeFileSync(kubeConfigPath, kubernetesCertificate.kubeConfig)
        step.debug(`kubeConfig: ${kubernetesCertificate.kubeConfig}`)
        step.info(`save kubeConfig to ${kubeConfigPath} successfully!`)

        kubectlArgs = [`--kubeconfig=${kubeConfigPath}`, `--insecure-skip-tls-verify=${params.insecureSkipTlsVerify}`]
    } else {
        // 新建空的config文件，实际通过 kubernetesCertificate.miranaProxy / kubernetesCertificate.jwtToken 来发起请求
        fs.writeFileSync(kubeConfigPath, '')
        // Set insecure skip TLS verify for ACK mode
        params.insecureSkipTlsVerify = true

        kubectlArgs = [`--kubeconfig=${kubeConfigPath}`, `--server=${kubernetesCertificate.miranaProxy}`, `--token=${kubernetesCertificate.jwtToken}`, `--insecure-skip-tls-verify=${params.insecureSkipTlsVerify}`]
    }

    kubectlArgs.push(`--namespace=${params.namespace}`)
    return kubectlArgs
}

export function execSyncReturnStdout(command: string): string {
    step.debug(`execSyncReturnStdout: ${command}`)

    let commandLog = ''
    try {
        commandLog = execSync(command).toString()
    } catch (e) {
        // 当指令执行非0退出时，stderr的内容会直接输出，并且生成一个 error 对象
        step.debug(`${e}`)
    }

    step.debug(`commandLog: ${commandLog}`)
    return commandLog
}

export function checkContainerConfig(params: IParams, output: string) {
    if (['deployments', 'statefulsets', 'daemonsets'].includes(params.kind)) {
        step.infoV1(polyglot.t("verify_container_configuration"))
        const jsonOutput = JSON.parse(output)
        const containerNames: string[] = jsonOutput.spec.template.spec.containers.map((container: any) => container.name)

        let count = 0
        let tmpName = params.containerName

        for (const name of containerNames) {
            tmpName = name
            count += 1
        }

        step.infoV1(polyglot.t("container_definitions",{
            name: params.name,
            count: count
        }))

        // hack 当容器数量为1时，页面配置的 containerName 将被真实值覆盖，无论 containerName 的取值
        if (count === 1) {
            step.debug(`set containerName value: ${tmpName}`)
            params.containerName = tmpName
        }
    }
}